import 'package:auto_route/auto_route.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:linux_do/config/GlobalSettingConfig.dart';
import 'package:linux_do/routes/AppRoutes.gr.dart';
import 'package:linux_do/service/NetworkService.dart';
import 'package:linux_do/service/RenderService.dart';
import 'package:material_symbols_icons/get.dart';
import 'package:super_tooltip/super_tooltip.dart';

class TopicListPage extends StatefulWidget {
  const TopicListPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return TopicListPageState();
  }
}

class TopicListPageState extends State<TopicListPage> {
  List<TopicData> data = [];
  ScrollController controller = ScrollController();
  int currentPage = 0;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ListView.builder(
        controller: controller,
        itemBuilder: (context, index) {
          var d = data[index];
          return ListViewItem(data: d);
        },
        itemCount: data.length,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _loadData();
    controller.addListener(() {
      double scrollPosition = controller.position.pixels;
      double maxScrollExtent = controller.position.maxScrollExtent;
      if (scrollPosition == maxScrollExtent) {
        print('已滚动到底部');
        _loadData(page: currentPage + 1);
      }
    });
  }

  Future<void> _loadData({int page = 0}) async {
    var data = await NetworkService.instance.topicList(page: page);
    if (mounted) {
      setState(() {
        this.data.addAll(data);
      });
    }
  }
}

class ListViewItem extends StatefulWidget {
  final TopicData data;

  const ListViewItem({super.key, required this.data});

  @override
  State<StatefulWidget> createState() {
    return ListViewItemState();
  }
}

class ListViewItemState extends State<ListViewItem> {
  Color _bgColor = Colors.white.withOpacity(0.3);

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) {
        setState(() {
          _bgColor = Colors.red;
        });
      },
      onExit: (_) {
        setState(() {
          _bgColor = Colors.white.withOpacity(0.3);
        });
      },
      child: GestureDetector(
        onTap: () {
          print(widget.data.id);
          context.router.replace(TopicContentPageRoute(data: widget.data));
        },
        child: Container(
          margin: const EdgeInsets.only(top: 5, bottom: 5),
          decoration: BoxDecoration(
              color: _bgColor, border: Border.all(color: Colors.red, width: 1)),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.only(left: 10),
                child: TopicAvatar(
                  poster: widget.data.posters[0],
                ),
              ),
              TopicContentZone(data: widget.data),
            ],
          ),
        ),
      ),
    );
  }
}

class TopicContentZone extends StatelessWidget {
  final TopicData data;

  const TopicContentZone({super.key, required this.data});

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.only(left: 10, right: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Flexible(
              flex: 4,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    data.title,
                    maxLines: 1,
                    style: const TextStyle(
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  data.tags.isEmpty
                      ? Container()
                      : SizedBox(
                          width: 100,
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            child: Row(
                              spacing: 5,
                              children: data.tags.map((e) {
                                return Text(
                                  e,
                                  style: TextStyle(
                                    backgroundColor: Colors.pink,
                                    foreground: Paint()..color = Colors.white,
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                ],
              ),
            ),
            Flexible(
              flex: 3,
              child: TopicReplyer(
                data: data,
              ),
            )
          ],
        ),
      ),
    );
  }
}

class TopicReplyer extends StatefulWidget {
  final TopicData data;

  const TopicReplyer({required this.data, super.key});

  @override
  State<TopicReplyer> createState() => _TopicReplyerState();
}

class _TopicReplyerState extends State<TopicReplyer> {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        int skip = 1;
        if (constraints.constrainWidth() <= 150) {
          skip = 5;
        }
        if (constraints.constrainWidth() > 150 &&
            constraints.constrainWidth() <= 180) {
          skip = 4;
        }
        if (constraints.constrainWidth() > 180 &&
            constraints.constrainWidth() <= 210) {
          skip = 3;
        }
        if (constraints.constrainWidth() > 210 &&
            constraints.constrainWidth() < 250) {
          skip = 2;
        }
        return Row(
          mainAxisAlignment: MainAxisAlignment.end,
          spacing: 5,
          children: widget.data.posters.skip(skip).map((e) {
            return e.avatar == null
                ? Container()
                : ReplyComponent(
                    poster: e,
                  );
          }).toList(),
        );
      },
    );
  }
}

class ReplyComponent extends StatefulWidget {
  final Poster poster;

  const ReplyComponent({required this.poster, super.key});

  @override
  State<StatefulWidget> createState() {
    return ReplyComponentState();
  }
}

class ReplyComponentState extends State<ReplyComponent> {
  final SuperTooltipController _controller = SuperTooltipController();

  @override
  Widget build(BuildContext context) {
    return SuperTooltip(
      controller: _controller,
      popupDirection: TooltipDirection.right,
      barrierColor: Colors.white.withOpacity(0.1),
      borderColor: Colors.pink,
      borderWidth: 1,
      backgroundColor: Colors.transparent,
      shadowColor: Colors.white,
      content: UserInfoComponent(user: widget.poster.user),
      child: MouseRegion(
        onHover: (_) {
          print(1);
          _controller.showTooltip();
        },
        child: Container(
          clipBehavior: Clip.hardEdge,
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(10)),
          ),
          child: CachedNetworkImage(
            imageUrl: '$host${widget.poster.avatar}',
            height: 25,
            width: 25,
            fadeOutDuration: const Duration(seconds: 3),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

class TopicAvatar extends StatefulWidget {
  final Poster poster;

  const TopicAvatar({super.key, required this.poster});

  @override
  State<TopicAvatar> createState() => _TopicAvatarState();
}

class _TopicAvatarState extends State<TopicAvatar> {
  SuperTooltipController _controller = SuperTooltipController();

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onHover: (_) {
        _controller.showTooltip();
      },
      child: SuperTooltip(
        controller: _controller,
        content: UserInfoComponent(user: widget.poster.user),
        popupDirection: TooltipDirection.right,
        barrierColor: Colors.white.withOpacity(0.1),
        borderColor: Colors.pink,
        borderWidth: 1,
        backgroundColor: Colors.transparent,
        shadowColor: Colors.white,
        child: Container(
          clipBehavior: Clip.hardEdge,
          decoration: const BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(15)),
          ),
          child: CachedNetworkImage(
            imageUrl: '$host${widget.poster.avatar}',
            width: 50,
            height: 50,
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

class UserInfoComponent extends StatefulWidget {
  final User? user;

  UserInfoComponent({super.key, this.user});

  @override
  State<UserInfoComponent> createState() => _UserInfoComponentState();
}

class _UserInfoComponentState extends State<UserInfoComponent> {
  double container_height = 0;

  @override
  void initState() {
    super.initState();
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   _updateContainerHeight();
    // });
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: NetworkService.instance.userCard(widget.user?.username ?? ''),
      builder: (BuildContext context, AsyncSnapshot<UserCard> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          var card = snapshot.data;
          return Container(
            width: 400,
            height: 300,
            decoration: BoxDecoration(
              image: card?.userInfo.card_background_upload_url == null
                  ? null
                  : DecorationImage(
                      fit: BoxFit.cover,
                      opacity: 0.3,
                      image: CachedNetworkImageProvider(
                        card?.userInfo.card_background_upload_url ?? '',
                      )),
            ),
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Stack(
                        children: [
                          SizedBox(
                            height: 70,
                            width: 70,
                            child: CachedNetworkImage(
                              imageUrl: card!.userInfo.avatar_template,
                              height: 50,
                              width: 50,
                            ),
                          ),
                          Positioned(
                            right: 10,
                            bottom: 10,
                            child: card.userInfo.flair_url == null
                                ? Container()
                                : CachedNetworkImage(
                                    height: 20,
                                    width: 20,
                                    imageUrl: card.userInfo.flair_url!),
                          ),
                        ],
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            card.userInfo.name ?? card.userInfo.username,
                            style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              fontStyle: FontStyle.italic,
                              foreground: Paint()..color = Colors.pink,
                            ),
                          ),
                          Text(card.userInfo.username),
                        ],
                      ),
                    ],
                  ),
                  Wrap(
                    children: [
                      // card.userInfo.bio_excerpt == null
                      //     ? Container()
                      //     : Text.rich(buildInput(card.userInfo.bio_excerpt!))
                    ],
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      card.userInfo.website == null
                          ? Container()
                          : Row(
                              children: [
                                Icon(SymbolsGet.get(
                                    'public', SymbolStyle.outlined)),
                                GestureDetector(
                                  onTap: () {},
                                  child: MouseRegion(
                                    cursor: SystemMouseCursors.click,
                                    child: Text(
                                      card.userInfo.website!,
                                      style: TextStyle(
                                          foreground: Paint()
                                            ..color = Colors.blue,
                                          fontWeight: FontWeight.bold),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                      Row(
                        spacing: 10,
                        children: [
                          Tooltip(
                              message: '最近活跃时间',
                              child: Icon(SymbolsGet.get(
                                  'schedule', SymbolStyle.outlined))),
                          Text(
                            card.userInfo.last_posted_at,
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                      Row(
                        spacing: 10,
                        children: [
                          Tooltip(
                              message: '加入日期',
                              child: Icon(SymbolsGet.get(
                                  'group', SymbolStyle.outlined))),
                          Text(
                            card.userInfo.cakedate,
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                      Row(
                        spacing: 10,
                        children: [
                          Tooltip(
                              message: '总浏览时长',
                              child: Icon(SymbolsGet.get('collections_bookmark',
                                  SymbolStyle.outlined))),
                          Text(
                            '${(card.userInfo.time_read / 3600).toInt()}小时',
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                      Row(
                        spacing: 10,
                        children: [
                          Tooltip(
                              message: '最近浏览时长',
                              child: Icon(SymbolsGet.get(
                                  'book_ribbon', SymbolStyle.outlined))),
                          Text(
                            '${(card.userInfo.recent_time_read / 3600).toInt()}小时',
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                        ],
                      )
                    ],
                  ),
                  Wrap(
                      spacing: 20,
                      alignment: WrapAlignment.spaceBetween,
                      children: card.badges.map((e) {
                        return SizedBox(
                          width: 185,
                          child: Row(
                            children: [
                              IconMap[e.id] ?? Container(),
                              Text(e.name),
                            ],
                          ),
                        );
                      }).toList())
                ],
              ),
            ),
          );
        } else {
          return const SizedBox(
            width: 0,
            height: 0,
          );
        }
      },
    );
  }
}
